/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {TreeNode} root
 * @return {number[][]}
 */
var levelOrder = function (root) {
  let ans = []
  if (root) {
    let queue = [root]
    let subPos = 1
    while (queue.length > 0) {
      let arr = []
      for (let i = 0; i < subPos; i++) {
        let tmp = queue.shift()
        if (tmp.left) queue.push(tmp.left)
        if (tmp.right) queue.push(tmp.right)
        arr.push(tmp.val)
      }
      subPos = queue.length
      ans.push(arr)
    }
  }
  return ans
}